package ymysql

import (
	"fmt"
	"log"

	"gitee.com/liuyongchina/go-library/config"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

//DB 启动时初始化DB
var err error

var schemas = make(map[string]*gorm.DB)

//GetDB 获取数据连接
func DB(schema string) *gorm.DB {
	if schemas[schema] != nil {
		return schemas[schema]
	}
	dbAll := config.NewDB().GetConfig()
	dbConfig := dbAll.Schema[schema]
	dsn := dbConfig.Username + ":" + dbConfig.Password + "@tcp(" + dbConfig.Host + ")/" + dbConfig.Schema + "?charset=utf8mb4&parseTime=True&loc=Local"
	fmt.Println("dns", dsn)
	schemas[schema], err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		log.Println(err)
	}
	return schemas[schema]
}
